package com.linran.javaweb.util;

import com.linran.javaweb.vo.PageVo;

import java.util.Map;
import java.util.Optional;

public class PageUtil {
    /**
     * 页码参数名称
     */
    public static final String PAGE_NO = "pageNo";
    /**
     * 页大小参数名称
     */
    public static final String PAGE_SIZE = "pageSize";
    /**
     * 默认页码:1
     */
    private static final Integer DEFAULT_PAGE_NO = 1;
    /**
     * 默认页大大小:50
     */
    private static final Integer DEFAULT_PAGE_SIZE = 50;
    /**
     * 页码参数
     */
    private static final ThreadLocal<Map<String, Integer>> PAGE_TL = new ThreadLocal<>();

    /**
     * 设置分页参数
     *
     * @param pageNo
     * @param pageSize
     */
    public static void setPageParam(Integer pageNo, Integer pageSize) {
        PAGE_TL.set(Map.of(PAGE_NO, Optional.ofNullable(pageNo).orElse(DEFAULT_PAGE_NO),
            PAGE_SIZE, Optional.ofNullable(pageSize).orElse(DEFAULT_PAGE_SIZE)));
    }

    /**
     * 清除threadLocal内容，防止内存泄露
     */
    public static void clear(){
        PAGE_TL.remove();
    }

    /**
     * 返回pageVO视图对象
     */
    public static PageVo getPageVO(Long total){
        Map<String, Integer> pageMap = PAGE_TL.get();
        return new PageVo(pageMap.get(PAGE_NO), pageMap.get(PAGE_SIZE), total);
    }
}
